import React from 'react'
import { useSelector } from 'react-redux'
import { Button, List, Popover, Avatar, Image } from 'antd'
import { UserOutlined } from '@ant-design/icons'
import styles from '../css/LoginAvatar.module.css'
import { useDispatch } from 'react-redux'
import { clearUserInfo, changeLoginStatus } from '../redux/userSlice.js'
import { useNavigate } from 'react-router-dom'
export default function LoginAvatar(props) {
  const { isLogin, userInfo } = useSelector((state) => state.user)

  let loginStatus = null
  const dispatch = useDispatch()
  const navigate = useNavigate()
  const listClickHandle = (item) => {
    if (item === '退出登录') {
      localStorage.removeItem('userToken')
      dispatch(clearUserInfo())
      dispatch(changeLoginStatus(false))
      navigate('/')
    } else {
      navigate('/personal')
    }
  }
  if (isLogin) {
    // 登录的
    const content = (
      <List
        bordered
        dataSource={['个人中心', '退出登录']}
        renderItem={(item) => (
          <List.Item style={{ cursor: 'pointer' }} onClick={() => listClickHandle(item)}>
            {item}
          </List.Item>
        )}
      />
    )

    loginStatus = (
      <Popover placement="bottom" content={content}>
        <div className={styles.avatarContainer}>
          <Avatar src={<Image preview={false} src={userInfo?.avatar} />} size="large" icon={<UserOutlined />} />
        </div>
      </Popover>
    )
  } else {
    // 没登录
    loginStatus = (
      <Button type="primary" size="large" onClick={props.loginHandle}>
        注册/登录
      </Button>
    )
  }

  return <div>{loginStatus}</div>
}
